package com.ruoyi.web.controller.product;

import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.IPaypalService;

/**
 * PayPal支付Controller
 *
 * @author ruoyi
 * @date 2025-04-13
 */
@RestController
@RequestMapping("/paypal")
public class PaypalController extends BaseController {

    @Autowired
    private IPaypalService paypalService;

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 创建支付
     */
    @PostMapping("/create/{orderId}")
    @Anonymous
    public AjaxResult createPayment(@PathVariable("orderId") String orderId) {
        return paypalService.createPayment(orderId);
    }

    /**
     * 执行支付
     */
    @GetMapping("/execute")
    @Anonymous
    public AjaxResult executePayment(
            @RequestParam("PayerID") String payerId,
            @RequestParam("token") String token) {
        return paypalService.executePayment(payerId, token);
    }

    /**
     * 支付回调
     */
    /**
     * 支付成功回调
     */
    @GetMapping("/callback")
    @Anonymous
    public void handleCallback(
            @RequestParam("PayerID") String payerId,
            @RequestParam("token") String token,
            @RequestParam(value = "orderId", required = false) String orderId,
            @RequestParam(value = "customerName", required = false) String customerName,
            HttpServletResponse response) throws Exception {

        // 处理支付回调逻辑
//        boolean paymentVerified = paypalService.handlePaypalCallback(payerId, token);

        // 构建成功页面并加入订单ID和客服名称
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html><head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<meta http-equiv=\"refresh\" content=\"0; url=/").append(customerName).append("/paypal-success.html?");

        // 添加参数
        if (orderId != null && !orderId.isEmpty()) {
            html.append("orderId=").append(orderId).append("&");
        }
        if (customerName != null && !customerName.isEmpty()) {
            html.append("customerName=").append(customerName);
        }
        html.append("\">");

        html.append("<title>支付成功</title>");
        html.append("</head><body>");
        html.append("<p>正在跳转到支付成功页面...</p>");
        html.append("</body></html>");

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(html.toString());
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status/{paymentId}")
    @Anonymous
    public AjaxResult checkPaymentStatus(@PathVariable("paymentId") String paymentId) {
        return paypalService.checkPaymentStatus(paymentId);
    }

    /**
     * 支付成功回调
     */
    @GetMapping("/success")
    @Anonymous
    public void successCallback(
            @RequestParam("PayerID") String payerId,
            @RequestParam("token") String token,
            HttpServletResponse response) throws Exception {
        Orders order = ordersMapper.selectOrdersByPaypalPaymentId(token);
        order.setOrderStatus(1);
        ordersMapper.updateOrdersByPaypalPaymentId(order);
        handleCallback(payerId, token, order.getOrderNo(), order.getCustomerNumber(), response);
    }

    /**
     * 支付取消回调
     */
    @GetMapping("/cancel")
    @Anonymous
    public void cancelCallback(
            @RequestParam("PayerID") String payerId,
            @RequestParam("token") String token,
            HttpServletResponse response) throws Exception {

        Orders order = ordersMapper.selectOrdersByPaypalPaymentId(token);
        order.setOrderStatus(3);
        ordersMapper.updateOrdersByPaypalPaymentId(order);
        // 构建取消页面并加入订单ID和客服名称
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html><head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<meta http-equiv=\"refresh\" content=\"0; url=/").append(order.getCustomerName()).append("/paypal-cancel.html?");
        // 添加参数
        if (StringUtils.isNotEmpty(order.getOrderNo())) {
            html.append("orderId=").append(order.getOrderNo()).append("&");
        }
        if (StringUtils.isNotEmpty(order.getCustomerName())) {
            html.append("customerName=").append(order.getCustomerName());
        }
        html.append("\">");

        html.append("<title>支付已取消</title>");
        html.append("</head><body>");
        html.append("<p>正在跳转到支付取消页面...</p>");
        html.append("</body></html>");

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(html.toString());
    }
} 